package com.xiaoxiao.spring.web;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;

public class TomcatServer {

	private String [] args;

	private Tomcat tomcat;

	public TomcatServer(String []args){
		tomcat = new Tomcat();
		this.args = args;
	}

	public void startServer(){
		Context context = new StandardContext();
		//context-path
		context.setPath("");
		tomcat.setPort(7886);
		DispatcherServlet dispathcerServlet = new DispatcherServlet();
		tomcat.addServlet(context,"dispathcerServlet",dispathcerServlet).setAsyncSupported(true);
		context.addServletMappingDecoded("/","dispathcerServlet");
		//监听器 通知 应用状态变化
		context.addLifecycleListener(new Tomcat.FixContextListener());
		//这行代码是在本地建立服务？
		tomcat.getHost().addChild(context);
		try {
			tomcat.start();
			Thread thread = new Thread(()->{
				tomcat.getServer().await();
			});
			thread.setDaemon(false);
			thread.start();
		} catch (LifecycleException e) {
			e.printStackTrace();
		}
	}
}
